package com.cjj.threadlocal;

class ThreadLocalDemo extends Thread{

    public Res res;

    public ThreadLocalDemo(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        for(int i = 0; i < 3; i ++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(getName() + "----" + i + ",number" + res.getNum());
        }
    }
}

class Res{
//    private int count = 0;
    /**
     * 设置本地线程的值，与共享变量进行隔离使用
     */
    private ThreadLocal<Integer> count = new ThreadLocal<Integer>(){
    @Override
    protected Integer initialValue() {
        return 0;
    }
};
    /**
     * 生成序列号
     * @return
     */
    public int getNum(){
        int num = count.get() + 1;
        count.set(num);
        return num;
    }
}

/**
 * @ClassName ThreadLocal_01
 * @Date 2021/07/18 21:15:15
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
public class ThreadLocal_01 {

    public static void main(String[] args) {
        Res res = new Res();
        ThreadLocalDemo t1 = new ThreadLocalDemo(res);
        ThreadLocalDemo t2 = new ThreadLocalDemo(res);
        ThreadLocalDemo t3 = new ThreadLocalDemo(res);
        t1.start();
        t2.start();
        t3.start();
    }

}
